package com.vone.export;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.vone.dao.GetCompany;
import com.vone.entity.Basicdata;

public class Export {
	/**
	 * 导出事件
	 * @param idList	企业赛事关联id
	 */
	public void exportbtnClickEvent(List<Map<String, String>> idList) {
		try {
			// 创建压缩文件
			String zipName = idList.get(0).get("groupType").toString() + idList.get(0).get("submitType").toString()
					+ "的企业信息_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
			JFileChooser jf = new JFileChooser();
			jf.setFileFilter(new FileNameExtensionFilter("ZIP压缩文件", new String[]{".zip"}));
			jf.setSelectedFile(new File(zipName));// 设置保存的文件

			if ((int) jf.showSaveDialog(null) == 0) {
				String filePath=jf.getSelectedFile().getAbsolutePath().toLowerCase();
				if(!filePath.endsWith(".zip")){
					filePath+=".zip";
				}
				ZipOutputStream out = new ZipOutputStream(new FileOutputStream(filePath));
				
				//先查询出所有的企业信息
				List<Basicdata> basicdataList = new ArrayList<Basicdata>();
				for (int i = 0; i < idList.size(); i++) {
					Basicdata basicdatas = GetCompany.actionDetail(idList.get(i).get("id"));
					basicdatas.setUserName(idList.get(i).get("userName"));
					basicdatas.setGroupType(idList.get(i).get("groupType").toString());
					basicdatas.setSubmitType(idList.get(i).get("submitType").toString());
					basicdataList.add(basicdatas);
				}
				
				//循环输出各个企业的excel文件
				for (int i = 0; i < basicdataList.size(); i++) {
					Basicdata basicdatas = basicdataList.get(i);
					ExportUntil.workbook = new HSSFWorkbook();
					// 创建企业基本信息和概况，第一个sheet
					CompanyBaseSheet companybase = new CompanyBaseSheet();
					companybase.getCompanySheet(basicdatas);
					// 创建股东信息，第二个sheet
					BossBaseSheet bossbasesheet = new BossBaseSheet();
					bossbasesheet.getBossBaseSheet(basicdatas);
					// 创建核心团队，第三个sheet
					TeamBaseSheet teambasesheet = new TeamBaseSheet();
					teambasesheet.getTeamBaseSheet(basicdatas);
					// 创建商业计划书，第四个sheet
					BusinessPlanBaseSheet businessplanbasesheet = new BusinessPlanBaseSheet();
					businessplanbasesheet.getBusinessPlanBaseSheet(basicdatas);
					// 创建创业服务，第五个sheet
					EntrepreneurshipServiceSheet entrepreneurshipservicesheet = new EntrepreneurshipServiceSheet();
					entrepreneurshipservicesheet.getEntrepreneurshipServiceSheet(basicdatas);

					ByteArrayOutputStream os = new ByteArrayOutputStream();
					ExportUntil.workbook.write(os);
					byte[] xls = os.toByteArray();
					zipFiles(out, MySecondaryStringFilter(MyStringFilter(basicdatas.getCompany_name())) + "（用户名："
							+ idList.get(i).get("userName") + "）.xls", new ByteArrayInputStream(xls));

					ExportUntil.workbook.close();//关闭当前excel文件流
				}
				out.close();
				JOptionPane.showMessageDialog(null, "导出成功!");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void zipFiles(ZipOutputStream out, String fileName, InputStream in) throws Exception {
		byte[] buf = new byte[1024];
		// 向输出流添加ZIP项
		out.putNextEntry(new ZipEntry(fileName));
		// 从文件传输字节到ZIP文件
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		// 完成写入
		out.closeEntry();
		in.close();
	}

	/**
	 * 压缩文件
	 * 
	 * @param listFile
	 *            File[] 需要压缩的文件列表
	 * @param zipfile
	 *            File 压缩后的文件
	 */
	// public static void zipFiles(List<File> listFile, File zipFile) {
	// byte[] buf = new byte[1024];
	// try {
	// //创建压缩文件
	// ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
	// //压缩文件
	// for (int i = 0; i < listFile.size(); i++) {
	// File file = listFile.get(i);
	// FileInputStream in = new FileInputStream(file);
	// //向输出流添加ZIP项
	// out.putNextEntry(new ZipEntry(file.getName()));
	// //从文件传输字节到ZIP文件
	// int len;
	// while ((len = in.read(buf)) > 0) {
	// out.write(buf, 0, len);
	// }
	// //完成写入
	// out.closeEntry();
	// in.close();
	// }
	// //完成压缩文件
	// out.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }

	/**
	 * 过滤特殊字符
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String MyStringFilter(String str) {
		// String regEx = "\\s";//清除一些字符
		// String
		// regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？
		// ]";//清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*+=|{}':;',\\[\\].<>/?~！@#￥%……&*——+|{}【】‘；：”“’。，、？ ]";// 清除掉所有特殊字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	/**
	 * 二次过滤特殊字符
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String MySecondaryStringFilter(String str) {
		String regEx = "\\s";// 清除一些字符
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}
}
